import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import React, { useState, useEffect } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import api from "../../api/api";
import { stati } from "../../api/api";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
function MyEditor({ setHtmls, fuhtml }) {
  // editor 实例
  //   const [editor, setEditor] = (useState < IDomEditor) | (null > null); // TS 语法
  const [editor, setEditor] = useState(null); // JS 语法

  // 编辑器内容
  const [html, setHtml] = useState("");
  // 工具栏配置
  const toolbarConfig = {}; // JS 语法

  // 编辑器配置
  const editorConfig = {
    // JS 语法
    placeholder: "请输入内容...",
    // 上传文件的配置
    MENU_CONF: {
      uploadImage: {
        server: api.adddetailimg,
        // 自定义增加 http  header
        headers: { Authorization: sessionStorage.getItem("token") },
        // form-data fieldName ，默认值 'wangeditor-uploaded-image'
        fieldName: "file",
        // // 单个文件的最大体积限制，默认为 2M
        maxFileSize: 1 * 1024 * 1024, // 1M
        // // 超时时间，默认为 10 秒
        timeout: 60 * 1000, // 5 秒
        customInsert(res, insertFn) {
          const { url } = res.data;
          // JS 语法
          // res 即服务端的返回结果

          // 从 res 中找到 url alt href ，然后插入图片
          insertFn(stati + url, "", "");
        },
      },
    },
  };
  const handleChange = (editor) => {
    setHtml(editor.getHtml());
    setHtmls(editor.getHtml());
  };
  useEffect(
    function () {
      setHtml(fuhtml);
    },
    [fuhtml]
  );
  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  return (
    <>
      <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: "1px solid #ccc" }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={(editor) => handleChange(editor)}
          mode="default"
          style={{ height: "500px", overflowY: "hidden" }}
        />
      </div>
      <div style={{ marginTop: "15px" }}>{html}</div>
    </>
  );
}

export default MyEditor;
